﻿using System;
using Csla.Xaml;
using BizControl.Presentation.Infrastructure.Controls;
using Csla;
using BizControl.Presentation.Infrastructure.Properties;
using System.Text;

namespace BizControl.Presentation.Infrastructure.Helpers
{
  public static class ConfirmationHelper
  {
    public static void ConfirmNavigationRequestSaveDlg<T>(ViewModel<T> model, Action<bool> continuationCallback)
      where T: BusinessBase<T>
    {
      if (model.Model.IsDirty)
      {
        var dlg = new ConfirmationDlg();

        if (!model.CanSave)
        {
          StringBuilder sb = new StringBuilder();
          sb.Append(Environment.NewLine);
          sb.Append(Environment.NewLine);
          sb.Append(Captions.SavingIsImpossibleDataContainsErrors);
          foreach (var item in model.Model.BrokenRulesCollection)
          {
            sb.Append(Environment.NewLine);
            sb.Append("-- ");
            sb.Append(item.Description);
          }
          dlg.tbContent.AppendText(sb.ToString());
          dlg.ConfirmButton.IsEnabled = false;
        }

        dlg.ShowDialog();
        if (dlg.Result == DlgResult.CancelWithoutSaving)
        {
          //model.Cancel(model, null);
          continuationCallback(true);
        }
        else if (dlg.Result == DlgResult.Confirm && model.CanSave)
        {
          model.Save(model, null);
          continuationCallback(true);
        }
        else continuationCallback(false);
      }
      else
      {
        continuationCallback(true);
      }
    }
  }
}
